Q := @

#CC := gcc
CC := arm-rockchip830-linux-uclibcgnueabihf-gcc
BLD_CFLAGS := $(CFLAGS) -Wall -Werror 
BLD_CFLAGS += -Os -fPIC

TOP_DIR := $(shell pwd)
DEMOS_DIR := demos
OUT_DIR := output
LIB_DIR := output/lib
INCLUDE_DIR := output/include
NOPOLL_DIR := components/remote-access/tunnel/src/nopoll/
BLD_LDFLAGS := $(LDFLAGS) -lpthread 

SRC_DIR := $(shell find . -type d \( ! -name demos \))

HDR_DIR := $(SRC_DIR)
BLD_CFLAGS += $(addprefix -I,$(HDR_DIR))

ra_exist = $(shell if [ -d $(NOPOLL_DIR) ]; then echo "true"; else echo "false"; fi)
ifeq ("$(ra_exist)", "true")
NOPOLL_SRC := $(shell find $(NOPOLL_DIR) -name "*.c")
NOPOLL_FILES := $(NOPOLL_SRC:.c=.o)
NOPOLL_FILES := $(addprefix $(OUT_DIR)/,$(NOPOLL_FILES))
NOPOLL_LIB := $(addprefix $(LIB_DIR)/, libnopoll.so)
EXT_LDFLAGS := -lnopoll -L $(LIB_DIR) -Wl,-rpath,$(LIB_DIR)

RA_DIR := components/remote-access/
RA_SRC := $(shell find $(RA_DIR) -not -path "*/nopoll/*" -name "*.c")
RA_FILES := $(RA_SRC:.c=.o)
RA_FILES := $(addprefix $(OUT_DIR)/,$(RA_FILES))

SRC_FILES := $(shell find . -not -path "*/demos/*.c" -not -path "*/remote-access/*" -name "*.c")
else
SRC_FILES := $(shell find . -not -path "*/demos/*.c" -name "*.c")
endif
OBJ_FILES := $(SRC_FILES:.c=.o)
OBJ_FILES := $(addprefix $(OUT_DIR)/,$(OBJ_FILES))

PROG_TARGET := $(subst _,-,$(patsubst %.c,%,$(wildcard demos/*_demo.c)))

INCLUDE_SRC := $(shell find . -not -path "*/output/*.h" -name "aiot_*_api.h")
AIOT_LIB := $(addprefix $(LIB_DIR)/, libaiot.so)

all: prepare $(NOPOLL_LIB) $(AIOT_LIB) $(PROG_TARGET)

prepare:
	$(Q)mkdir -p $(OUT_DIR)
	$(Q)mkdir -p $(LIB_DIR)
	$(Q)mkdir -p $(INCLUDE_DIR)
	$(Q)cp $(INCLUDE_SRC) $(INCLUDE_DIR)

$(NOPOLL_LIB): $(NOPOLL_FILES) 
	$(Q)echo "+ Linking $(LIB_DIR)/$(notdir $@) ..."
	$(Q)$(CC) -fPIC -shared -o $@ $^

$(AIOT_LIB): $(OBJ_FILES) $(RA_FILES)
	$(Q)echo "+ Linking $(LIB_DIR)/$(notdir $@) ..."
	$(Q)$(CC) -fPIC -shared -o $@ $^ $(EXT_LDFLAGS)

$(PROG_TARGET): $(OBJ_FILES) $(RA_FILES)
	$(Q)echo "+ Linking $(OUT_DIR)/$(notdir $@) ..."
	$(Q)mkdir -p $(dir $@)
	$(Q)if [ $(notdir $@) = "remote-access-basic-demo" ] \
		|| [ $(notdir $@) = "tunnel-basic-demo" ] \
		|| [ $(notdir $@) = "tunnel-switch-demo" ];then \
		$(CC) -o $@ \
			$(patsubst $(OUT_DIR)/%,%,$(addsuffix .c,$(subst $(notdir $@),$(subst -,_,$(notdir $@)),$@))) \
			$(BLD_CFLAGS) $^ $(BLD_LDFLAGS) $(EXT_LDFLAGS); \
	else \
		$(CC) -o $@ \
			$(patsubst $(OUT_DIR)/%,%,$(addsuffix .c,$(subst $(notdir $@),$(subst -,_,$(notdir $@)),$@))) \
			$(BLD_CFLAGS) $(OBJ_FILES) $(BLD_LDFLAGS); \
	fi

	$(Q)mv $@ $(OUT_DIR)

$(OUT_DIR)/%.o: %.c
	$(Q)echo ": Compiling $< ..."
	$(Q)mkdir -p $(OUT_DIR)/$(dir $<)
	$(Q)$(CC) -o $@ -c $< $(BLD_CFLAGS)

clean:
	$(Q)rm -rf $(OUT_DIR)